package Work;
import java.io.File;
import java.io.IOException;

//import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {
	Document doc;
	String filepath;
	Node root;
	ModifyXMLFile(){
		filepath = "/argumento.xml";
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		try {
			docBuilder = docFactory.newDocumentBuilder();
			doc = docBuilder.parse(filepath);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void initial(){
		// Get the root element
		root = doc.getFirstChild();
		NodeList nodeList= root.getChildNodes();
		for(int i=0;i<nodeList.getLength();i++){
			System.out.println(nodeList.item(i).getNodeName());
		}
	}

	public String deletNode(String name){


		//NodeList list = root.getChildNodes();

			Node nodeDeled = doc.getElementsByTagName(name).item(0);
			System.out.println(nodeDeled.getParentNode().getNodeName()+" my father");
			nodeDeled.getParentNode().removeChild(nodeDeled);		
		
		// write the content into xml file
		
		try {
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer;
			transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(filepath));
			transformer.transform(source, result);

			System.out.println("Done");
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "no se elimino ningun nodo";
	}
	/*public static void main(String argv[]) {
		ModifyXMLFile j =new ModifyXMLFile();
		j.initial();
		System.out.println(j.deletNode(JOptionPane.showInputDialog("nodo")));

	}*/
}